using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Agriculture.Domain;
using Dapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;

namespace Agriculture.Api.Read.Application.Handler
{
    /// <summary>
    /// 挂号订单查询处理器
    /// </summary>
    public class RegistrationOrderQueryHandler : IRequestHandler<RegistrationOrderQuery, RegistrationOrderQueryResult>
    {
        /// <summary>
        /// 配置接口
        /// </summary>
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration">配置接口</param>
        public RegistrationOrderQueryHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 处理挂号订单查询请求
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>挂号订单查询结果，包含分页信息和订单列表</returns>
        public async Task<RegistrationOrderQueryResult> Handle(RegistrationOrderQuery request, CancellationToken cancellationToken)
        {
            var result = new RegistrationOrderQueryResult();
            string connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new MySqlConnection(connectionString))
            {
                // 构建查询条件
                var conditions = new List<string>();
                var parameters = new DynamicParameters();

                // 只查询未删除的订单
                conditions.Add("ro.IsDeleted = 0");

                // 就诊人姓名或订单号或用户名查询
                if (!string.IsNullOrEmpty(request.SearchKey))
                {
                    conditions.Add("(p.Name LIKE @SearchKey OR ro.OrderNo LIKE @SearchKey OR u.UserName LIKE @SearchKey)");
                    parameters.Add("@SearchKey", $"%{request.SearchKey}%");
                }

                // 时间范围查询 - 开始时间
                if (request.StartTime.HasValue)
                {
                    conditions.Add("ro.SubmitTime >= @StartTime");
                    parameters.Add("@StartTime", request.StartTime.Value);
                }

                // 时间范围查询 - 结束时间
                if (request.EndTime.HasValue)
                {
                    conditions.Add("ro.SubmitTime <= @EndTime");
                    parameters.Add("@EndTime", request.EndTime.Value.AddDays(1).AddSeconds(-1)); // 结束时间为当天23:59:59
                }

                // 订单状态查询
                if (request.OrderStatus.HasValue && request.OrderStatus.Value > 0)
                {
                    // 1：待支付，2：已完成，3：已取消，4：已退款
                    int statusCode = 0;
                    switch (request.OrderStatus.Value)
                    {
                        case 1:
                            statusCode = 1; // 待支付状态码
                            break;
                        case 2:
                            statusCode = 2; // 已完成状态码
                            break;
                        case 3:
                            statusCode = 3; // 已取消状态码
                            break;
                        case 4:
                            statusCode = 4; // 已退款状态码
                            break;
                    }

                    conditions.Add("ro.Status = @OrderStatus");
                    parameters.Add("@OrderStatus", statusCode);
                }

                // 构建WHERE子句
                var whereClause = conditions.Count > 0 ? $" WHERE {string.Join(" AND ", conditions)}" : string.Empty;

                // 统计总记录数
                var countSql = @"
                    SELECT COUNT(1) 
                    FROM registrationordermodel ro 
                    LEFT JOIN patientmodel p ON ro.PatientName = p.Name
                    LEFT JOIN usermodel u ON ro.UserId = u.Id
                    LEFT JOIN doctormodel d ON ro.DoctorName = d.Name" + whereClause;
                
                var totalCount = await connection.ExecuteScalarAsync<int>(countSql, parameters);

                // 计算总页数
                int totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                // 设置分页结果属性
                result.CurrentPage = request.PageIndex;
                result.TotalCount = totalCount;
                result.TotalPages = totalPages;

                // 如果没有数据，直接返回空列表
                if (totalCount == 0)
                {
                    result.RegistrationOrders = new List<RegistrationOrderDto>();
                    return result;
                }

                // 计算分页偏移量
                int offset = (request.PageIndex - 1) * request.PageSize;

                // 查询分页数据
                var querySql = @"
                    SELECT ro.OrderNo, ro.SubmitTime, u.UserName, 
                           d.Department, d.Name AS Doctor, ro.ServiceFee, ro.Status AS OrderStatusCode
                    FROM registrationordermodel ro
                    LEFT JOIN patientmodel p ON ro.PatientName = p.Name
                    LEFT JOIN usermodel u ON ro.UserId = u.Id
                    LEFT JOIN doctormodel d ON ro.DoctorName = d.Name
                    " + whereClause + @"
                    ORDER BY ro.SubmitTime DESC
                    LIMIT @Offset, @Limit";

                // 添加分页参数
                parameters.Add("@Offset", offset);
                parameters.Add("@Limit", request.PageSize);

                // 执行查询
                var orders = await connection.QueryAsync<dynamic>(querySql, parameters);

                // 转换查询结果为DTO对象列表
                var orderList = new List<RegistrationOrderDto>();
                foreach (var order in orders)
                {
                    var item = new RegistrationOrderDto
                    {
                        OrderNo = order.OrderNo,
                        SubmitTime = order.SubmitTime,
                        UserName = order.UserName,
                        Department = order.Department,
                        Doctor = order.Doctor,
                        RegistrationFee = order.ServiceFee,
                        OrderStatus = ConvertOrderStatus(order.OrderStatusCode)
                    };
                    orderList.Add(item);
                }

                result.RegistrationOrders = orderList;
                return result;
            }
        }

        /// <summary>
        /// 转换订单状态码为状态文本
        /// </summary>
        /// <param name="status">状态码</param>
        /// <returns>状态文本</returns>
        private string ConvertOrderStatus(int status)
        {
            switch (status)
            {
                case 1:
                    return "待支付";
                case 2:
                    return "已完成";
                case 3:
                    return "已取消";
                case 4:
                    return "已退款";
                default:
                    return "未知";
            }
        }
    }
} 